
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import sys
import os
import cryptography  # 显式导入cryptography以确保正确加载

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# 使用绝对导入
from student.model.student_model import Student
from student.service.student_service import StudentService
from student.repository.mysql_repository import MySQLStudentRepository
from student.configuration.student_configuration import StudentSettings

# 导入工具类
from eureka_client.eureka import EurekaServiceRegistrar
from jeager.jeager_service import JaegerService
from Prothemeus.prothemeus import PrometheusService

# 初始化配置
settings = StudentSettings()

# 初始化 MySQL 连接池
mysql_repository = MySQLStudentRepository()
student_service = StudentService(mysql_repository)

# 初始化 FastAPI 应用
app = FastAPI()

# 添加CORS支持
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"] ,  # 允许所有来源，生产环境应限制特定域名
    allow_credentials=True,
    allow_methods=["*"],  # 允许所有HTTP方法
    allow_headers=["*"],  # 允许所有HTTP头
)

# 定义数据库连接处理事件
@app.on_event("startup")
async def startup_db_client():
    """启动时初始化数据库连接"""
    await mysql_repository.connect()

@app.on_event("shutdown")
async def shutdown_db_client():
    """关闭时释放数据库连接"""
    await mysql_repository.close()

# 调用工具类
# 1. 添加Prometheus监控
PrometheusService.setup_prometheus(app, app_name="student-service")

# 2. 添加Jaeger分布式追踪
JaegerService.setup_jaeger(app, "student-service", settings.port)

# 3. 注册到Eureka服务中心
eureka_registrar = EurekaServiceRegistrar(
    app=app,
    app_name="student-service",
    port=settings.port
)

@app.get("/students", response_model=list[Student])
async def get_all_students():
    """获取所有学生信息接口"""
    return await student_service.get_all_students()

# 如果直接运行此文件，启动服务
if __name__ == "__main__":
    import uvicorn
    uvicorn.run("student.main:app", host="0.0.0.0", port=settings.port, reload=True)
